package com.health.viewscontrols.sbcl;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import com.contec.jar.BC401.BC401_Data;
import com.contec.jar.BC401.BC401_Struct;
import com.contec.jar.BC401.DeviceCommand;
import com.contec.jar.BC401.DevicePackManager;
import com.health.viewscontrols.NovaActivity;
import com.health.viewscontrols.NovaApplication;
import com.health.R;
import com.health.tablebean.BTDevice;
import com.health.tablebean.SBCL_DATA;
import com.health.tools.GlobalConts;
import com.health.widget.TJShowDialog;
import com.novabluetooth.services.bluetooth2.MeasureActivity;
import com.novabluetooth.services.hqxd.HQXDActivity;
import com.novabluetooth.services.ktxyj.KTXYJActivity;
import com.novabluetooth.services.lbxd.LBXD_MainActivity;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 设备测量
 * 
 * @author nova
 *
 */
public class SBCLMainActivity2 extends NovaActivity implements OnClickListener {

	private Button btn_back;
	private Button btn_up;

	private TextView title;
	private TextView tv_lbxd;
	private TextView tv_ktxyj;
	private TextView tv_hqxy;
	private TextView tv_aikanghb;// 艾康血红蛋白
	private TextView tv_kangtainiaoji;// 康泰尿液分析仪
	boolean isKangTaiNiaoJi = false;
	// private TextView tv_kangtaixindian;// 康泰心电工作站
	/**
	 * 康泰尿机
	 */
	BluetoothAdapter adapter;// 蓝牙适配器
	IntentFilter intentFilter;
	private String deviceName;// 设备名称
	String deviceAddress;// 设备地址
	DevicePackManager mPackManager;
	String uroString;
	String bloString;
	String bilString;
	String ketString;
	String leuString;
	String gluString;
	String proString;
	String phString;
	String nitString;
	String sgString;
	String ascString;
	String IDCARD;// 身份证号
	SimpleDateFormat df;// 时间格式
	public String str_result = "";
	// boolean scanecg = false;// 是否为搜搜索康泰心电工作站

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sbcl_main2);
		if (NovaApplication.getUserInfo() != null) {
			IDCARD = NovaApplication.getUserInfo().getIDCARD();
		}
		setIntentFilter();
		registerReceiver(mReceiver, intentFilter);
		df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		findViews();
		setListeners();

	}

	@Override
	public void findViews() {
		btn_back = (Button) findViewById(R.id.btn_back);
		btn_up = (Button) findViewById(R.id.btn_up);
		btn_up.setVisibility(View.GONE);

		title = (TextView) findViewById(R.id.title);
		title.setText("设备测量");
		tv_lbxd = (TextView) findViewById(R.id.tv_lbxd);
		tv_ktxyj = (TextView) findViewById(R.id.tv_ktxyj);
		tv_hqxy = (TextView) findViewById(R.id.tv_hqxy);
		tv_aikanghb = (TextView) findViewById(R.id.tv_aikanghb);
		tv_kangtainiaoji = (TextView) findViewById(R.id.tv_kangtainiaoji);
		// tv_kangtaixindian = (TextView) findViewById(R.id.tv_kangtaixindian);
	}

	@Override
	public void setListeners() {
		btn_back.setOnClickListener(this);
		tv_lbxd.setOnClickListener(this);
		tv_ktxyj.setOnClickListener(this);
		tv_hqxy.setOnClickListener(this);
		tv_aikanghb.setOnClickListener(this);
		tv_kangtainiaoji.setOnClickListener(this);
		// tv_kangtaixindian.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// scanecg = false;
//		if(NovaApplication.bloothTool!=null){
//			NovaApplication.bloothTool.scanLeDevice(false); 
//		}
		Intent intent = null;
		Bundle bundle = new Bundle();
		int id = v.getId();
		if (id == R.id.btn_back) {
			isKangTaiNiaoJi = false;
			SBCLMainActivity2.this.finish();
		} else if (id == R.id.tv_lbxd) {
			isKangTaiNiaoJi = false;
			intent = new Intent(getApplicationContext(), LBXD_MainActivity.class);
		} else if (id == R.id.tv_ktxyj) {
			isKangTaiNiaoJi = false;
			intent = new Intent(getApplicationContext(), KTXYJActivity.class);
		} else if (id == R.id.tv_hqxy) {
			isKangTaiNiaoJi = false;
			intent = new Intent(getApplicationContext(), HQXDActivity.class);
		} else if (id == R.id.tv_aikanghb) {
			isKangTaiNiaoJi = false;
			bundle.putString("MeasureItem", "NOVAHB");
			intent = new Intent();
			intent.setClass(SBCLMainActivity2.this, MeasureActivity.class);
			intent.putExtras(bundle);
			SBCLMainActivity2.this.startActivity(intent);
			SBCLMainActivity2.this.finish();
		} else if (id == R.id.tv_kangtainiaoji) {
			kangTaiNiaoJi();
			GlobalConts.showProgressDialog(mContext, "正在查找设备");
		} else {
		}

		if (intent != null) {
			startActivity(intent);
		}
	}

	public void kangTaiNiaoJi() {
		initBlooth();
		doDiscovery();
		
		mPackManager = new DevicePackManager();
	
		isKangTaiNiaoJi = true;

	}

	/**
	 * 康泰ECG
	 * 
	 * @author 鹿云龙
	 * @date 2016年9月30日 下午3:46:25
	 */
	// @Deprecated
	// public void kangTaiECG() {
	// initBlooth();
	// doDiscovery();
	// setIntentFilter();
	// mPackManager = new DevicePackManager();
	// registerReceiver(mReceiver, intentFilter);
	// }

	// 初始化蓝牙
	public void initBlooth() {
		// 检查设备是否支持蓝牙
		adapter = BluetoothAdapter.getDefaultAdapter();
		if (adapter == null) {
			Toast.makeText(getApplicationContext(), "该设备不支持蓝牙", Toast.LENGTH_SHORT).show();
		}
		// 打开蓝牙
		if (!adapter.isEnabled()) {
			Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
			// 设置蓝牙可见性，最多300秒
			intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
			startActivity(intent);
		}
	}

	// 搜索蓝牙设备
	private void doDiscovery() {

		try {
			// 返回设备是否正在发现周围蓝牙设备
			if (adapter.isDiscovering()) {
				// 取消正在发现远程蓝牙设备的过程
				if (!adapter.cancelDiscovery()) {
					Toast.makeText(getApplicationContext(), "BluetoothAdapter正处于扫描状态", Toast.LENGTH_SHORT).show();
				}
			}
			// 开始发现过程
			adapter.startDiscovery();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 设置广播信息过滤
	public void setIntentFilter() {
		intentFilter = new IntentFilter();
		intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
		intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
		intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
		intentFilter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
		intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
	}

	public BroadcastReceiver mReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (BluetoothDevice.ACTION_FOUND.equals(action)) {

				// ----其他-------------------------------------------------------------------------------
				BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

				deviceName = device.getName();

				System.out.println("扫描到的设备名称为：" + deviceName);
				if (deviceName != null && deviceName.contains("BC014")) {
					deviceAddress = device.getAddress();
					List<BTDevice> btDevices = NovaApplication.fdbmanger.findAllBTByWhere(BTDevice.class,
							"macAddress = " + "'" + device.getAddress() + "'");
					if (btDevices.size() > 0) {
						System.out.println("扫描到蓝牙设备");
						adapter.cancelDiscovery();
						// if (device.getBondState() ==
						// BluetoothDevice.BOND_BONDED)
						// {
						try {
							// 连接
							connect(device);
						} catch (IOException e) {
							e.printStackTrace();
							System.out.println(e);
						}
					} else {
						GlobalConts.showToast(SBCLMainActivity2.this, "该康泰尿液分析仪未被绑定，请先绑定设备");
					}

				}
			} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
				System.out.println("本轮扫描蓝牙设备结束");
			}

		}
	};

	private void connect(BluetoothDevice device) throws IOException {
		// 固定的UUID
		final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
		UUID uuid = UUID.fromString(SPP_UUID);
		final BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuid);
		new Thread(new Runnable() {

			@Override
			public void run() {
				GlobalConts.closeProgressDialog();
				try {

					socket.connect();
					new ConnectedThread(socket).start();
					mHandler.sendEmptyMessage(0);

				} catch (IOException e) {
					mHandler.sendEmptyMessage(1);

					e.printStackTrace();
				}

			}

		}).start();

	}

	private class ConnectedThread extends Thread {
		private final BluetoothSocket mmSocket;
		private final InputStream mmInStream;
		private final OutputStream mmOutStream;

		public ConnectedThread(BluetoothSocket socket) {
			mmSocket = socket;
			InputStream tmpIn = null;
			OutputStream tmpOut = null;

			try {
				tmpIn = socket.getInputStream();
				tmpOut = socket.getOutputStream();
				byte[] readData = DeviceCommand.Request_AllData();
				tmpOut.write(readData);
			} catch (IOException e) {
			}

			mmInStream = tmpIn;
			mmOutStream = tmpOut;
		}

		public void run() {
			GlobalConts.closeProgressDialog();
			byte[] buffer = new byte[1024];
			int bytes;
			boolean run = true;
			while (run) {
				try {
					bytes = mmInStream.read(buffer);
					byte backByte = mPackManager.arrangeMessage(buffer, buffer.length);
					switch (backByte) {
					case (byte) 0x05:
						BC401_Data backData = mPackManager.mBc401_Data;
						ArrayList<BC401_Struct> list = backData.Structs;
						System.out.println("数据长度" + list.size());
						mmOutStream.write(DeviceCommand.Delete_AllData());
						if (list.size() > 0) {
							int[] niaoYeBuffer = { list.get(0).URO, list.get(0).BLD, list.get(0).BIL, list.get(0).KET,
									list.get(0).GLU, list.get(0).PRO, list.get(0).PH, list.get(0).NIT, list.get(0).LEU,
									list.get(0).SG, list.get(0).VC };
							Message msg = new Message();
							Bundle b = new Bundle();// 存放数据
							b.putIntArray("niaoYeBuffer", niaoYeBuffer);
							msg.setData(b);
							msg.what = 3;
							mHandler.sendMessage(msg);
						}

						break;
					case (byte) 0x04:
						mHandler.sendEmptyMessage(2);
						break;
					}
					// if((buffer[9] & 0xff) == 0x9f){
					// byte[] _commd_Handshake = { (byte) 0xaa, (byte) 0xaa,
					// (byte) 0xaa, (byte) 0x96, (byte) 0x69,
					// (byte) 0x00, (byte) 0x03, (byte) 0x20, (byte) 0x02,
					// (byte) 0x21 };
					// mmOutStream.write(_commd_Handshake);
					// }else if(buffer.length > 18 && (buffer[18] & 0xff) ==
					// 0x9c){
					// byte[] _commd_Handshake = { (byte) 0xaa, (byte) 0xaa,
					// (byte) 0xaa, (byte) 0x96, (byte) 0x69,
					// (byte) 0x00, (byte) 0x03, (byte) 0x30, (byte) 0x01,
					// (byte) 0x32 };
					// mmOutStream.write(_commd_Handshake);
					// }
				} catch (IOException e) {

					if (mmInStream != null) {
						try {
							mmInStream.close();
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					}

					break;
				} catch (Exception e) {
					// TODO Auto-generated catch block
					if (mmInStream != null) {
						try {
							mmInStream.close();
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					}

				}
			}
		}
	}

	public void getNiaoYe(int[] niaoYeBuffer) {
		for (int i = 0; i < niaoYeBuffer.length; i++) {
			switch (i) {
			case 0:// 尿胆原
				int uro = niaoYeBuffer[i];
				if (uro == 0) {
					uroString = "Norm";
				} else if (uro == 1) {
					uroString = "1+";
				} else if (uro == 2) {
					uroString = "2+";
				} else if (uro == 3) {
					uroString = ">=3+";
				}
				break;
			case 1:// 潜血
				int blo = niaoYeBuffer[i];
				if (blo == 0) {
					bloString = "-";
				} else if (blo == 1) {
					bloString = "+-";
				} else if (blo == 2) {
					bloString = "1+";
				} else if (blo == 3) {
					bloString = "2+";
				} else if (blo == 4) {
					bloString = "3+";
				}
				break;
			case 2:// 胆红素
				int bil = niaoYeBuffer[i];
				if (bil == 0) {
					bilString = "-";
				} else if (bil == 1) {
					bilString = "1+";
				} else if (bil == 2) {
					bilString = "2+";
				} else if (bil == 3) {
					bilString = "3+";
				}
				break;
			case 3:// 酮体
				int ket = niaoYeBuffer[i];
				if (ket == 0) {
					ketString = "-";
				} else if (ket == 1) {
					ketString = "1+";
				} else if (ket == 2) {
					ketString = "2+";
				} else if (ket == 3) {
					ketString = "3+";
				}
				break;
			case 4:// 葡萄糖
				int glu = niaoYeBuffer[i];
				if (glu == 0) {
					gluString = "-";
				} else if (glu == 1) {
					gluString = "+-";
				} else if (glu == 2) {
					gluString = "1+";
				} else if (glu == 3) {
					gluString = "2+";
				} else if (glu == 4) {
					gluString = "3+";
				} else if (glu == 5) {
					gluString = "4+";
				}
				break;
			case 5:// 蛋白质
				int pro = niaoYeBuffer[i];
				if (pro == 0) {
					proString = "-";
				} else if (pro == 1) {
					proString = "+-";
				} else if (pro == 2) {
					proString = "1+";
				} else if (pro == 3) {
					proString = "2+";
				} else if (pro == 4) {
					proString = ">=3+";
				}
				break;
			case 6:// PH值
				int ph = niaoYeBuffer[i];
				if (ph == 0) {
					phString = "5";
				} else if (ph == 1) {
					phString = "6";
				} else if (ph == 2) {
					phString = "7";
				} else if (ph == 3) {
					phString = "8";
				} else if (ph == 4) {
					phString = "9";
				}
				break;
			case 7:// 亚硝酸盐
				int nit = niaoYeBuffer[i];
				if (nit == 0) {
					nitString = "-";
				} else if (nit == 1) {
					nitString = "1+";
				}
				break;
			case 8:// 白细胞
				int leu = niaoYeBuffer[i];
				if (leu == 0) {
					leuString = "-";
				} else if (leu == 1) {
					leuString = "+-";
				} else if (leu == 2) {
					leuString = "1+";
				} else if (leu == 3) {
					leuString = "2+";
				} else if (leu == 4) {
					leuString = "3+";
				}
				break;
			case 9:// 比重
				int sg = niaoYeBuffer[i];
				if (sg == 0) {
					sgString = "<=1.005";
				} else if (sg == 1) {
					sgString = "1.010";
				} else if (sg == 2) {
					sgString = "1.015";
				} else if (sg == 3) {
					sgString = "1.020";
				} else if (sg == 4) {
					sgString = "1.025";
				} else if (sg == 5) {
					sgString = ">=1.030";
				}
				break;
			case 10:// 维生素C
				int asc = niaoYeBuffer[i];
				if (asc == 0) {
					ascString = "-";
				} else if (asc == 1) {
					ascString = "+-";
				} else if (asc == 2) {
					ascString = "1+";
				} else if (asc == 3) {
					ascString = "2+";
				} else if (asc == 4) {
					ascString = "3+";
				}
				break;
			default:
				break;
			}
		}
		str_result = "尿胆原:" + uroString + ",尿潜血:" + bloString + ",胆红素:" + bilString + ",尿酮体:" + ketString + ",尿糖:"
				+ gluString + ",尿蛋白:" + proString + ",PH:" + phString + ",亚硝酸盐:" + nitString + ",白细胞:" + leuString
				+ ",比重:" + sgString + ",维生素:" + ascString;
		UUID uuidNiaoYe = UUID.randomUUID();
		String dateNiaoYe = df.format(new Date());
		// 存尿胆原
		saveCLData("诺安尿液分析仪", "尿液分析仪", "尿胆原", uroString, "尿胆原", uuidNiaoYe.toString(), IDCARD, dateNiaoYe);
		// 存潜血
		saveCLData("诺安尿液分析仪", "尿液分析仪", "潜血", bloString, "潜血", uuidNiaoYe.toString(), IDCARD, dateNiaoYe);
		// 存胆红素
		saveCLData("诺安尿液分析仪", "尿液分析仪", "胆红素", bilString, "胆红素", uuidNiaoYe.toString(), IDCARD, dateNiaoYe);

		// 存酮体
		saveCLData("诺安尿液分析仪", "尿液分析仪", "酮体", ketString, "酮体", uuidNiaoYe.toString(), IDCARD, dateNiaoYe);
		// 葡萄糖
		saveCLData("诺安尿液分析仪", "尿液分析仪", "葡萄糖", gluString, "葡萄糖", uuidNiaoYe.toString(), IDCARD, dateNiaoYe);
		// 蛋白质
		saveCLData("诺安尿液分析仪", "尿液分析仪", "蛋白质", proString, "蛋白质", uuidNiaoYe.toString(), IDCARD, dateNiaoYe);
		// PH
		saveCLData("诺安尿液分析仪", "尿液分析仪", "PH", phString, "酸碱度", uuidNiaoYe.toString(), IDCARD, dateNiaoYe);
		// 亚硝酸盐
		saveCLData("诺安尿液分析仪", "尿液分析仪", "亚硝酸盐", nitString, "亚硝酸盐", uuidNiaoYe.toString(), IDCARD, dateNiaoYe);
		// 白细胞
		saveCLData("诺安尿液分析仪", "尿液分析仪", "白细胞", leuString, "白细胞", uuidNiaoYe.toString(), IDCARD, dateNiaoYe);
		// 比重
		saveCLData("诺安尿液分析仪", "尿液分析仪", "比重", sgString, "比重", uuidNiaoYe.toString(), IDCARD, dateNiaoYe);
		// 维生素
		saveCLData("诺安尿液分析仪", "尿液分析仪", "维生素", ascString, "维生素", uuidNiaoYe.toString(), IDCARD, dateNiaoYe);
		showTJDialog(str_result);
	}

	public void saveCLData(String device_name, String device_type, String cl_type, String cl_value, String cl_type_name,
			String GUID, String IDCARD, String cl_time) {
		SBCL_DATA sbcl_Data = new SBCL_DATA();
		sbcl_Data.setDEVICE_NAME(device_name);
		sbcl_Data.setDEVICE_TYPE(device_type);
		sbcl_Data.setCL_TYPE(cl_type);
		sbcl_Data.setCL_VALUE(cl_value);
		sbcl_Data.setCL_TYPE_NAME(cl_type_name);
		sbcl_Data.setGUID(GUID);
		sbcl_Data.setIDCARD(IDCARD);
		sbcl_Data.setCL_TIME(cl_time);
		sbcl_Data.setIS_UPDATE("Y");
		NovaApplication.fdbmanger.save(sbcl_Data);
	}

	private TJShowDialog tjDialog;

	/**
	 * 显示文本信息
	 */
	public void showTJDialog(String text) {
		if (tjDialog == null) {
			tjDialog = new TJShowDialog(this);
		}
		tjDialog.setText(text);
		tjDialog.show();
	}
//	@Override
//	protected void onPause() {
//		super.onPause();
//		if (isKangTaiNiaoJi) {
//			this.unregisterReceiver(mReceiver);
//		}
//	}
	@Override
	protected void onDestroy() {
		super.onDestroy();

		// Make sure we're not doing discovery anymore
		if (adapter != null) {
			adapter.cancelDiscovery();
		}

//		if (isKangTaiNiaoJi) {
			this.unregisterReceiver(mReceiver);
//		}

	/*	Intent intent3 = new Intent(getApplicationContext(), NoticeService.class);
		startService(intent3);*/
//			if(NovaApplication.bloothTool!=null){
//				NovaApplication.bloothTool.scanLeDevice(true);
//			}

	}

	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				GlobalConts.showProgressDialog(SBCLMainActivity2.this, "正在获取数据");
				break;
			case 1:
				GlobalConts.showToast(SBCLMainActivity2.this, "连接失败，请重试");
				break;
			case 2:
				GlobalConts.showToast(SBCLMainActivity2.this, "无数据");
				break;
			case 3:
				GlobalConts.closeProgressDialog();
				int[] niaoYeBuffer = msg.getData().getIntArray("niaoYeBuffer");
				getNiaoYe(niaoYeBuffer);
				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		// switch (requestCode) {
		// case REQUEST_ENABLE_BT:
		// if (resultCode != Activity.RESULT_OK) {
		// Toast.makeText(this, "bt_not_enabled", Toast.LENGTH_SHORT).show();
		// finish();
		// }
		// }
	}
	// 康泰心电--------------------------------------------------------------------
}
